package com.changgou.util;

import com.changgou.file.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

public class FastDFSClient {   //文件上传,下载,上传等工具类

    static {

        //用来动态获得文件的绝对路径
        String path = new ClassPathResource("fdfs_client.conf").getPath();


        try {
            ClientGlobal.init(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //提取公有代码
    /***
     * 获取TrackerServer
     */
    public static TrackerServer getTrackerServer() throws Exception{

        TrackerClient trackerClient = new TrackerClient();

        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }


    /***
     * 获取StorageClient
     * @return
     * @throws Exception
     */
    public static StorageClient getStorageClient() throws Exception{

        TrackerServer trackerServer = getTrackerServer();

        StorageClient storageClient = new StorageClient(trackerServer,null);

        return  storageClient;
    }


        /****
         * 文件上传
         * @param file : 要上传的文件信息封装->FastDFSFile
         * @return String[]
         *          1:文件上传所存储的组名
         *          2:文件存储路径
         */
        public static String[] upload(FastDFSFile file){

            try {
                TrackerClient trackerClient = new TrackerClient();

                TrackerServer trackerServer = trackerClient.getConnection();

                StorageClient storageClient = new StorageClient(trackerServer,null);

                NameValuePair[] meta_list = new NameValuePair[]{new NameValuePair(file.getName()),new NameValuePair(file.getAuthor())};

                //用来下载
                //参数一 :文件的名字
                //文件的扩展名: jpg
                //元数据 : 作者,名字

                String[] strings = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);

                return  strings;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return  null;
        }


        //
}
